package com.info.dbase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;

import com.info.utils.ConfigManager;

/**
 * @author HAHA
 * 
 */
public class Connections {
	private static Logger logger=Logger.getLogger(Connections.class);
	private static DataSource dataSource = null;
	private static BasicDataSource ds = null;
	public static boolean flag = false;

	/**
	 *获取连接
	 * @return
	 * @throws SQLException
	 * @throws Exception
	 */
	public static synchronized Connection getConnection() throws SQLException,
			Exception {
		Connection conns = null;
		try {
			if (!flag) {
				if (dataSource == null)
					initPool();
				conns = dataSource.getConnection();
			} else {
				Class.forName(ConfigManager.jdrivers);

				conns = DriverManager.getConnection(ConfigManager.jurl,
						ConfigManager.juser, ConfigManager.jpass);
			}
		} catch (SQLException e) {
			throw e;
		} catch (Exception e1) {
			throw e1;
		}
		return conns;
	}

	/**
	 * 关闭连接
	 * @param conns
	 */
	public static void close(Connection conns) {
		try {
			if ((conns != null) && (!conns.isClosed()))
				conns.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化连接池
	 * @throws SQLException
	 */
	private static void initPool() throws SQLException {
		if (ds != null) {
			try {
				ds.close();
			} catch (SQLException e) {
				throw e;
			}
			ds = null;
		}
		flag = false;
		ds = new BasicDataSource();
		ds.setDriverClassName(ConfigManager.jdrivers);
		ds.setUsername(ConfigManager.juser);
		ds.setPassword(ConfigManager.jpass);
		ds.setUrl(ConfigManager.jurl);
		ds.setMaxActive(ConfigManager.jmax);
		ds.setMaxIdle(ConfigManager.jmin);
		dataSource = ds;
		logger.info("SHW#数据库连接池初始化成功,数据库地址:" + ConfigManager.jurl);
		logger.info("SHW#数据库用户:" + ConfigManager.juser + "最大连接数:"
				+ ConfigManager.jmax + "最小连接数:" + ConfigManager.jmin);
	}

	/**
	 * 关闭连接池
	 */
	public static void shutDown() {
		if (ds != null)
			try {
				ds.close();
			} catch (SQLException localSQLException) {
			}
		ds = null;
		dataSource = null;
	}

	public static void main(String[] str) {
		Connection conns = null;
		try {
			conns = getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		close(conns);
	}
}
